class VoronoiTreemapChart {
  constructor(selector, config) {
    this.svg = d3.select(selector);
    this.width = config.width || 800;
    this.height = config.height || 600;
    this.colorScheme = config.colorScheme || d3.schemeSet2;
    this.padding = config.padding || 20;
    this.clip = [
      [this.padding, this.padding],
      [this.width - this.padding, this.padding],
      [this.width - this.padding, this.height - this.padding],
      [this.padding, this.height - this.padding]
    ];
  }

  render(data) {
    const root = d3.hierarchy(data).sum(d => d.weight || 1);
    const voronoiTreemap = d3.voronoiTreemap().clip(this.clip);
    voronoiTreemap(root);

    const svg = this.svg.attr("width", this.width).attr("height", this.height);
    svg.selectAll("*").remove(); // 清空旧内容

    const leaves = root.leaves();

    // 多边形节点
    svg.selectAll("path")
      .data(leaves)
      .enter()
      .append("path")
      .attr("d", d => "M" + d.polygon.join("L") + "Z")
      .attr("fill", (d, i) => d.data.color || this.colorScheme[i % 10])
      .attr("stroke", "#fff")
      .attr("stroke-width", 1.2)
      .on("mouseover", function (event, d) {
        d3.select(this).attr("stroke", "#000").attr("stroke-width", 2);
        tooltip.style("visibility", "visible").html(
          `<b>${d.data.name}</b><br>
           所属模块：${d.parent.data.name}<br>
           专利数量：${d.data.weight}`
        );
      })
      .on("mousemove", function (event) {
        tooltip.style("top", (event.pageY + 10) + "px")
               .style("left", (event.pageX + 10) + "px");
      })
      .on("mouseout", function () {
        d3.select(this).attr("stroke", "#fff").attr("stroke-width", 1.2);
        tooltip.style("visibility", "hidden");
      });

    // 标签
    svg.selectAll("text")
      .data(leaves)
      .enter()
      .append("text")
      .attr("x", d => d.polygon.site.x)
      .attr("y", d => d.polygon.site.y)
      .style("font-size", "10px")
      .attr("text-anchor", "middle")
      .style("fill", "#111")
      .text(d => d.data.name.split("公司")[0]);

    // Tooltip
    const tooltip = d3.select("body").append("div")
      .attr("class", "tooltip")
      .style("position", "absolute")
      .style("background", "rgba(255,255,255,0.9)")
      .style("border", "1px solid #999")
      .style("padding", "5px 8px")
      .style("border-radius", "5px")
      .style("font-size", "12px")
      .style("visibility", "hidden");
  }
}